import { Modal, notification } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import permissionService from '@/api/services/security/permissionService';
import { PermissionSearchForm } from '@/pages/management/system/permission/permission-search-form';
import ProTag from '@/theme/antd/components/tag';
import { pagination } from '@/utils/pagination';

import { ListData, Permission, Role } from '#/entity';

export type PermissionSelectModalProps = {
  title: string;
  show: boolean;
  role: Role;
  onOk: VoidFunction;
  onCancel: VoidFunction;
};

export function PermissionSelect({
  title,
  show,
  role,
  onOk,
  onCancel,
}: PermissionSelectModalProps) {
  const [searchData, setSearchData] = useState<PermissionSearchForm>({
    page: 1,
    take: 10,
  });
  const [tableData, setTableData] = useState<ListData<Permission>>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    permissionService.PermissionList(searchData).then((data) => {
      setTableData(data);
    });
    if (role.id) {
      permissionService.rolePermissionList(role.id!).then((data) => {
        const ids = data.map((item) => item.id!);
        setSelectedRowKeys(ids);
      });
    }
  }, [role.id, searchData]);

  const onSelect = (selected, trueFalse) => {
    if (trueFalse) {
      setSelectedRowKeys([...selectedRowKeys, selected.id]);
    } else {
      selectedRowKeys.splice(selectedRowKeys.indexOf(selected.id), 1);
      setSelectedRowKeys([...selectedRowKeys]);
    }
  };
  const rowSelection: TableRowSelection<Permission> = {
    selectedRowKeys,
    onSelect,
  };
  const onConfirm = () => {
    permissionService.roleAssign(role.id!, { ids: selectedRowKeys }).then(() => {
      notification.success({ message: '授权成功' });
      onOk();
    });
  };
  const columns: ColumnsType<Permission> = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 300,
    },
    {
      title: '模块',
      dataIndex: 'module',
      width: 60,
      render: (_, record) => <ProTag color="processing">{record.module?.name}</ProTag>,
    },
    {
      title: '是否只读',
      dataIndex: 'isImmutable',
      width: 60,
      render: (isImmutable: boolean) => {
        if (isImmutable) {
          return <ProTag color="processing">是</ProTag>;
        }
        return <ProTag color="processing">否</ProTag>;
      },
    },
  ];
  return (
    <Modal
      title={title}
      open={show}
      onOk={onConfirm}
      onCancel={onCancel}
      width={600}
      destroyOnHidden
    >
      <Table
        rowKey="id"
        rowSelection={rowSelection}
        size="small"
        scroll={{ x: 'max-content' }}
        pagination={pagination({
          page: searchData,
          onPageChange: (page, rows) => {
            setSearchData((prev) => ({
              ...prev,
              page,
              take: rows,
            }));
          },
          count: tableData?.count,
        })}
        columns={columns}
        dataSource={tableData?.data}
      />
    </Modal>
  );
}
